package utils

import (
	"context"
	"fmt"
	"time"

	"enterprise-base/internal/config"

	"github.com/go-redis/redis/v8"
)

var client *redis.Client

// 初始化Redis客户端
func InitRedis() error {
	// 创建连接配置
	opt := redis.Options{
		Addr:     fmt.Sprintf("%s:%d", config.GlobalRedisConfig.Host, config.GlobalRedisConfig.Port),
		Password: config.GlobalRedisConfig.Password, // no password set
		DB:       config.GlobalRedisConfig.DB,       // use default DB
	}

	// 连接Redis
	client = redis.NewClient(&opt)

	// 检查连接
	_, err := client.Ping(context.Background()).Result()
	if err != nil {
		return err
	}

	return nil
}

// SetKey 设置键值对
func RedisSetKey(ctx context.Context, key, value string, expiration time.Duration) error {
	return client.Set(ctx, key, value, expiration).Err()
}

// GetKey 获取键的值
func RedisGetKey(ctx context.Context, key string) (*string, error) {
	val, err := client.Get(ctx, key).Result()
	if err != nil {
		return nil, err
	}
	return &val, nil
}

// DelKey 删除键
func RedisDelKey(ctx context.Context, key string) (int64, error) {
	return client.Del(ctx, key).Result()
}

// ExpireKey 设置键的过期时间
func RedisExpireKey(ctx context.Context, key string, duration time.Duration) (bool, error) {
	return client.Expire(ctx, key, duration).Result()
}

func RedisSetExpireKey(ctx context.Context, key, value string, expiration time.Duration) error {
	return client.SetEX(ctx, key, value, expiration).Err()
}
